<template>
  <Form
      ref="formRef"
      v-model="initFormData"
      :model="formState"
      class="md:flex-row w-full flex-wrap"
      v-bind="formItemLayout"
  >
    <div class="md:flex w-full md:justify-start">
      <Col :span="6">
        <FormItem label="应用" name="appId" style="width: 185px">
          <div class="md:w-30">
            <Select
                v-model:value="appId"
                :allowClear="true"
                :options="appOptions"
                placeholder="请选择应用"
                @change="onAppChange"
            >
            </Select>
          </div>
        </FormItem>
      </Col>
      <Col :span="6">
        <FormItem label="租户" name="tenant" style="width: 165px">
          <div class="md:w-30">
            <Select
                v-model:value="tenantCode"
                :allowClear="true"
                :disabled="tenantDisabled"
                :options="tenantOptions"
                placeholder="请选择租户"
            >
            </Select>
          </div>
        </FormItem>
      </Col>
    </div>
    <div class="md:flex w-full md:justify-between">
      <div class="md:flex md:justify-start">
        <Col :span="10">
          <FormItem label="步长" name="stepType">
            <div class="md:w-18">
              <Select
                  v-model:value="step"
                  :allowClear="true"
                  :options="stepType"
                  @change="onSelectChange"
              >
              </Select>
            </div>
          </FormItem>
        </Col>
        <Col :span="20">
          <FormItem label="时间" name="time">
            <div class="md:flex">
              <div class="md:w-28">
                <DatePicker
                    v-model:value="startValue"
                    :disabled="pickerDisabled"
                    :disabled-date="disabledStartDate"
                    :format="format"
                    :open="startOpenShow"
                    :picker="mode"
                    :placeholder="startPlaceholder"
                    @openChange="handleStartOpenChange"
                    @panelChange="handleStartPanelChange"
                />
              </div>
              <span> ~ </span>
              <div class="md:w-28">
                <DatePicker
                    v-model:value="endValue"
                    :disabled="pickerDisabled"
                    :disabled-date="disabledEndDate"
                    :format="format"
                    :open="endOpenShow"
                    :picker="mode"
                    :placeholder="endPlaceholder"
                    @openChange="handleEndOpenChange"
                    @panelChange="handleEndPanelChange"
                />
              </div>
            </div>
          </FormItem>
        </Col>
      </div>
      <Col :span="2">
        <FormItem>
          <div class="md:flex md:justify-end">
            <Button shape="circle" type="primary" @click="onSubmit">
              <template #icon>
                <SearchOutlined/>
              </template>
            </Button>
            <Button shape="circle" style="margin-left: 5px" @click="resetForm">
              <template #icon>
                <RedoOutlined/>
              </template>
            </Button>
          </div>
        </FormItem>
      </Col>
    </div>
  </Form>
</template>

<script lang="ts" setup>
import {Button, Col, DatePicker, Form, FormItem, Select} from 'ant-design-vue';
import {computed, onMounted, reactive, ref} from 'vue';
import {RedoOutlined, SearchOutlined} from '@ant-design/icons-vue';
import {Moment} from 'moment';
import {
  AppTemplateResp,
  TenantByAppListReq,
  TenantByAppListResp,
} from '/@/api/operation-center/common/model/commonModel';
import {getAppSelectList, getTenantListByApp} from '/@/api/operation-center/common/common';
import {
  AppSubAnalysisByTenantReqDto
} from '/@/api/operation-center/tenant-opertation/app-subscription-analysis/model/appSubscriptionModel';


const props = defineProps({
  initData: Object,
})
let initFormData = computed(() => props.initData);

const formRef = ref();

const formState = reactive<Record<string, any>>({});

const formItemLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 24},
};

// Select 组件属性设置
const tenantCode = ref();
const tenantOptions = ref<any[]>([]);

const appId = ref();
const appOptions = ref<any[]>([]);

const step = ref();
const stepType = [
  {label: '按月', value: 0},
  {label: '按年', value: 1},
];

const startValue = ref<Moment | undefined>();
const startPlaceholder = ref<string>('开始月份');
const startOpenShow = ref<boolean>(false);
const endValue = ref<Moment>();
const endPlaceholder = ref<string>('结束月份');
const endOpenShow = ref<boolean>(false);
const format = ref<string>('YYYY-MM');
const pickerDisabled = ref<boolean>(true);
const tenantDisabled = ref<boolean>(true);
const mode = ref('month');
const emits = defineEmits(['success']);

function convertTenantOptions(res: TenantByAppListResp[]) {
  let options: any[] = [];
  for (let i = 0; i < res.length; i++) {
    let tenantItem = res[i];
    let tenantOption = {
      label: tenantItem.tenantName,
      value: tenantItem.tenantCode,
    };
    options.push(tenantOption);
  }
  tenantOptions.value = options;
}

function convertAppOptions(res: AppTemplateResp[]) {
  let options: any[] = [];
  for (let i = 0; i < res.length; i++) {
    let appItem = res[i];
    let appOption = {
      label: appItem.name,
      value: appItem.id,
    };
    options.push(appOption);
  }
  appOptions.value = options;
}

const onAppChange = (data) => {
  if (data !== null && data != undefined && data.length != 0) {
    let tenantByAppReq: TenantByAppListReq = {
      appId: data,
    };

    getTenantListByApp(tenantByAppReq).then((res) => {
      tenantDisabled.value = false
      convertTenantOptions(res);
    });
  }
};

const onSelectChange = (val) => {
  if (typeof val == 'undefined') {
    pickerDisabled.value = true;
  } else if (val !== 0 && !val) {
    pickerDisabled.value = true;
  } else if (val === 0) {
    pickerDisabled.value = false;
    startPlaceholder.value = '开始月份';
    endPlaceholder.value = '结束月份';
    mode.value = 'month';
    format.value = 'YYYY-MM';
  } else if (val === 1) {
    pickerDisabled.value = false;
    startPlaceholder.value = '开始年份';
    endPlaceholder.value = '结束年份';
    mode.value = 'year';
    format.value = 'YYYY';
  } else {
    pickerDisabled.value = true;
  }
};

const disabledStartDate = (startValue: Moment) => {
  if (!startValue || !endValue.value) {
    return false;
  }
  return startValue.valueOf() > endValue.value.valueOf();
};

const disabledEndDate = (endValue: Moment) => {
  if (!endValue || !startValue.value) {
    return false;
  }

  return startValue.value.valueOf() >= endValue.valueOf();
};

const handleStartOpenChange = (open: boolean) => {
  if (!open) {
    startOpenShow.value = false;
    endOpenShow.value = true;
  } else {
    startOpenShow.value = true;
  }
};

const handleEndOpenChange = (open: boolean) => {
  endOpenShow.value = open;
};

const handleStartPanelChange = (value) => {
  startValue.value = value;
  startOpenShow.value = false;
};

const handleEndPanelChange = (value) => {
  endValue.value = value;
  endOpenShow.value = false;
};

// 提交表单参数
const onSubmit = async () => {
  formRef.value.validate().then(() => {

    let appSubAnalysisByTenantReq: AppSubAnalysisByTenantReqDto = {
      tenantCode: tenantCode.value,
      appId: appId.value,
      stepType: step.value,
      startTime: startValue.value.format('YYYY-MM-DD HH:mm:ss'),
      endTime: endValue.value.format('YYYY-MM-DD HH:mm:ss'),
    };

    emits('success', appSubAnalysisByTenantReq);
  });
};

// 清空表单参数
const resetForm = () => {
  appId.value = undefined;
  step.value = undefined;
  startValue.value = undefined;
  endValue.value = undefined;
  pickerDisabled.value = true;
};

onMounted(() => {
  getAppSelectList().then((res) => {
    convertAppOptions(res);
  });
});


</script>
